<template>
  <div>
    <el-card>
      <el-table :data="skuArr">
        <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
        <el-table-column show-overflow-tooltip label="名称" prop="skuName" width="150px"></el-table-column>
        <el-table-column show-overflow-tooltip label="描述" prop="skuDesc" width="150px"></el-table-column>
        <el-table-column label="默认图片">
          <template #="{ row }">
            <el-image :src="row.skuDefaultImg" style="width: 100px; height: 100px"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="质量(g)" prop="weight" width="150px"></el-table-column>
        <el-table-column label="价格(元)" prop="price" width="150px"></el-table-column>
        <el-table-column label="操作" width="210px" fixed="right">
          <template #="{ row }">
            <el-button :type="row.isSale == 1 ? (row.type = 'info') : (row.type = 'success')
              " size="small" @click="updateSale(row)" :icon="row.isSale == 1 ? 'Bottom' : 'Top'"
              :title="row.isSale == 1 ? '下架' : '上架'"></el-button>
            <el-button type="primary" size="small" @click="update" icon="Edit"></el-button>
            <el-button type="info" size="small" @click="viewSku(row)" icon="InfoFilled"></el-button>

            <!-- Popconfirm 气泡确认框 -->
            <el-popconfirm @confirm="deleteSku(row.id)" :title="`你确定要删除${row.skuName}`" width="180px">
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
        :background="true" layout="prev, pager, next, jumper,->,total,sizes" :total="total" />

      <!-- SKU抽屉组件--展示SKU详情 -->
      <!-- 
        v-model="drawer" drawer控制是否显示
        direction="rtl" 抽屉的方向，默认为从右到左，我们使用默认即可
       -->
      <el-drawer v-model="drawer" direction="rtl">
        <!-- 标题 -->
        <template #header>
          <h4>查看商品详情</h4>
        </template>
        <template #default>
          <!-- 采用栅格系统 -->
          <el-row>
            <el-col :span="6">名称</el-col>
            <el-col :span="18">{{ skuDetail.skuName }}</el-col>
          </el-row>
          <el-row>
            <el-col :span="6">描述</el-col>
            <el-col :span="18">{{ skuDetail.skuDesc }}</el-col>
          </el-row>
          <el-row>
            <el-col :span="6">价格</el-col>
            <el-col :span="18">{{ skuDetail.price }}</el-col>
          </el-row>
          <el-row>
            <el-col :span="6">平台属性</el-col>
            <el-col :span="18">
              <el-tag style="margin: 0px 5px" v-for="(item) in skuDetail.skuAttrValueList" :key="item.id">
                {{ item.valueName }}
              </el-tag>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">销售属性</el-col>
            <el-col :span="18">
              <el-tag style="margin: 0px 5px" v-for="(item) in skuDetail.skuSaleAttrValueList" :key="item.id">
                {{ item.saleAttrValueName }}
              </el-tag>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">商品图片</el-col>
            <el-col :span="18">
              <!-- 轮播图 -->
              <el-carousel :interval="4000" type="card" height="200px">
                <el-carousel-item v-for="item in skuDetail.skuImageList" :key="item.id">
                  <el-image :src="item.imgUrl" style="width: 100%; height: 100%"></el-image>
                </el-carousel-item>
              </el-carousel>
            </el-col>
          </el-row>
        </template>
      </el-drawer>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import {
  reqSKUList,
  reqOnSale,
  reqCancelSale,
  reqSkuINFO,
  reqDeleteSku,
} from '@/api/product/sku'
import type {
  SkuResponseData,
  SkuData,
  SkuINFOResponseData,
} from '@/api/product/sku/type'
import { ElMessage } from 'element-plus/lib/components/index.js'
import { ref, reactive, onMounted, watch } from 'vue'
// 保存当前页码
let pageNo = ref<number>(1)
// 每页保存几条数据
let pageSize = ref<number>(10)
// 保存返回的数据总数
let total = ref<number>(0)
// 保存已有的SKU数组
let skuArr = ref<SkuData[]>([])
// 控制是否显示抽屉组件
let drawer = ref<boolean>(false)
// 存储sku详情的数据
let skuDetail = reactive<SkuData>({
  spuId: '',
  price: 0,
  skuName: '',
  skuDesc: '',
  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
})

// 组件加载完以后立刻获取SKU数据
onMounted(() => {
  getSKU()
})

// 获取SKU数据
const getSKU = async (pageNum = pageNo.value) => {
  // 查询sku的数据默认从当前页开始，如果指定页数就从指定的页数开始
  pageNo.value = pageNum
  let result: SkuResponseData = await reqSKUList(pageNo.value, pageSize.value)
  if (result.code == 200) {
    skuArr.value = result.data.records
    total.value = result.data.total
  }
}

// 当前页码发生变化的时候再次发请求获取已有SPU数据展示，从用户点击的页码
watch(pageNo, () => {
  console.log('当前页发生变化了,当前页为->', pageNo.value)
  getSKU()
})

// 当下拉菜单(3条/每页|5条/每页)发生变化的时候触发
watch(pageSize, () => {
  console.log('每页有几条数据,每页的数据量->', pageSize)
  // 当前页码发生变化的时候再次发请求获取已有SPU数据展示,从1页面开始
  getSKU(1)
})

// 更新SKU上下架的回调函数
const updateSale = async (row: SkuData) => {
  // 控制商品的上架与下架，当isSale为1，表示该商品已经上架，需要更新为下架；否则为已经下架，需要更新为上架
  if (row.isSale == 1) {
    let result1 = await reqCancelSale(row.id as number)
    if ((result1.code = 200)) {
      ElMessage({ type: 'success', message: '下架成功' })

      // 上架成功后，需要再次获取更新后的数据, 默认从当前页开始
      getSKU()
    } else {
      ElMessage({ type: 'error', message: '下架失败' })
    }
  } else {
    let result2 = await reqOnSale(row.id as number)
    if ((result2.code = 200)) {
      ElMessage({ type: 'success', message: '上架成功' })
      // 下架成功后，需要再次获取更新后的数据, 默认从当前页开始
      getSKU()
    } else {
      ElMessage({ type: 'error', message: '上架失败' })
    }
  }
}

// 更新已有的SKU的接口
const update = () => {
  ElMessage({ type: 'success', message: '程序员努力的研发中...' })
}

// 查看SKU详情的回调
const viewSku = async (row: SkuData) => {
  drawer.value = true
  // 首先要清空之前的数据
  Object.assign(skuDetail, {
    spuId: '',
    price: '',
    skuName: '',
    skuDesc: '',
    skuImageList: [],
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
  })
  let result: SkuINFOResponseData = await reqSkuINFO(row.id as number)
  if (result.code == 200) {
    // 存储已有的SKU
    Object.assign(skuDetail, result.data)
  }
}

// 删除SKU
const deleteSku = async (skuId: number) => {
  let result: any = await reqDeleteSku(skuId)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' })
    // 删除成功，重新获取SKU数据。如果当前页的总数据大于1，则删除后继续停留在当前页；如果当前页的数据总数小于1；则删除后需要返回当前页的上一页
    getSKU(skuArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({ type: 'error', message: `删除失败${result.data}` })
  }
}
</script>
<script lang="ts">
export default {
  name: 'ProductSKU',
}
</script>
<style scoped lang="scss">
.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
</style>
